package com.ilink.ilinkcommon.interceptors;

import cn.hutool.core.util.StrUtil;
import com.ilink.ilinkcommon.utils.UserContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * <h3>new-ilink-java-backend</h3>
 *
 * @author LiuZheng
 * @description <p>请求拦截并获取用户信息</p>
 * @date 2024-09-16 00:03
 **/
public class UserInfoInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
        Object handler) throws Exception {
        // 获取用户id
        String userId = request.getHeader("userId");

        // 判断是否获取了用户id，若获取到，存入ThreadLocal
        if (StrUtil.isNotBlank(userId)) {
            UserContext.setUserId(userId);
        }

        // 放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
        Object handler, Exception ex) throws Exception {
        // 请求结束后清除ThreadLocal
        UserContext.removeUserId();
    }
}
